<template>
  <div>
    <div class="card" style="margin-bottom: 20px; margin-top: 10px">
      <el-input style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入用户名查询" prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="warning" @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleDeleteBatch">批量删除</el-button>
<!--      <el-button type="info">导入</el-button>-->
<!--      <el-button type="success">导出</el-button>-->
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe size="large" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="年龄" prop="age" />
        <el-table-column label="性别" prop="sex" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <el-dialog title="用户信息" v-model="data.formVisible" width="500">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding-right: 40px; padding-top: 20px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="data.form.sex">
            <el-radio value="男" label="男"></el-radio>
            <el-radio value="女" label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number style="width: 180px" :min="18" v-model="data.form.age" autocomplete="off"  placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="data.form.email" autocomplete="off" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {Delete, Edit, Search} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  ids: [],
  form: {
    name: '',
    username: '',
    sex: '',
    age: null,
    phone: '',
    email: ''
  },
  rules: {
    name: [
      {required: true, message: '请输入姓名', trigger: 'blur'},
      {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
    ],
    username: [
      {required: true, message: '请输入用户名', trigger: 'blur'},
      {min: 2, message: '长度应大于 2 个字符' , trigger: 'blur'}
    ],
    sex: [
      {required: true, message: '请选择性别', trigger: 'blur'},
    ],
    age: [
      {required: true, message: '请输入年龄', trigger: 'blur'},
    ],
    phone: [
      {required: true, message: '请输入电话号码', trigger: 'blur'},
      {min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur'}
    ],
    email: [
      {required: true, message: '请输入邮箱', trigger: 'blur'},
      {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
    ]
  }
})

const formRef = ref()

const load = () => {
  request.get('user/selectPage', {
    params:{
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    data.tableData = res.data.list
    data.total = res.data.total
  })
}

const reset = () => {
  data.name = null
  load()
}

const handleAdd = () => {
  data.formVisible = true
  data.form = {}
}

const handleEdit = (row) => {
  data.formVisible = true
  data.form = JSON.parse(JSON.stringify(row)) //深拷贝 生成个新对象，用于编辑
}

const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      data.form.id ? update() : add()
    }else {
      ElMessage.warning('请填写正确的信息')
    }
  })
}

const add = () => {
  request.post('user/insert', data.form).then(res => {
    if (res.code == 200) {
      ElMessage.success("新增成功")
      data.formVisible = false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put('user/update', data.form).then(res => {
    if (res.code == 200) {
      ElMessage.success("修改成功")
      data.formVisible = false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete('/user/delete/' +row.id).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}

const handleSelectionChange = (rows) => {  // 返回所有选中的行对象数组
  // 从选中的行数组里面取出所有行的id组成一个新的数组
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

const handleDeleteBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(() => {
    request.delete('/user/deleteBatch', { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        load()  // 删除后一定要重新加载最新的数据
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch()
}



load()
</script>

<style scoped>

</style>